import json
from selenium import webdriver
import time

from selenium.webdriver.common.by import By


def create_chrome_driver(*, headless=False):  # 创建谷歌浏览器对象，用selenium控制浏览器访问url
    options = webdriver.ChromeOptions()
    if headless:  # 如果为True，则爬取时不显示浏览器窗口
        options.add_argument('--headless')

    # 做一些控制上的优化
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)
    # 创建浏览器对象
    browser = webdriver.Chrome(options=options,
                               executable_path="chromedriver.exe")
    # 破解反爬措施
    browser.execute_cdp_cmd(
        'Page.addScriptToEvaluateOnNewDocument',
        {'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'}
    )

    return browser


def add_cookies(browser, cookie_file):  # 给浏览器对象添加登录的cookie
    with open(cookie_file, 'r') as file:
        cookie_list = json.load(file)
        for cookie_dict in cookie_list:
            if cookie_dict['secure']:
                browser.add_cookie(cookie_dict)


if __name__ == '__main__':
    browser = create_chrome_driver()
    browser.get('https://login.taobao.com')

    # 隐式等待
    browser.implicitly_wait(10)

    # 获取页面元素模拟用户输入和点击行为
    username_input = browser.find_element(By.CSS_SELECTOR, '#fm-login-id')
    username_input.send_keys('1940952395')  # 填写用户名

    password_input = browser.find_element(By.CSS_SELECTOR, '#fm-login-password')
    password_input.send_keys('LCD1940952395')  # 填写对应的密码

    # 登录按钮
    login_button = browser.find_element(By.CSS_SELECTOR, '#login-form > div.fm-btn > button')
    login_button.click()
    # 显示等待
    # wait_obj = WebDriverWait(browser, 10)
    # wait_obj.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, 'div.m-userinfo')))
    time.sleep(15)

    # 获取登录的cookie数据，并且写入文件
    with open('taobao1.json', 'w') as file:
        json.dump(browser.get_cookies(), file)

    browser.close()
